package com.comleader.operator.service.strategy;

import static cn.hutool.core.util.CharsetUtil.CHARSET_GBK;
import static com.comleader.operator.common.constant.Constant.*;
import static com.comleader.operator.common.constant.DictConstant.PERSONAL_IDCARD_TYPE;
import static com.comleader.operator.common.constant.DictConstant.PERSONAL_NOT_NET_STATE;
import static com.comleader.operator.common.enums.InspectStatusEnum.FAILED;
import static com.comleader.operator.common.enums.StatisticsTypeEnum.NONCOMPLIANT;
import static com.comleader.operator.common.enums.StatisticsTypeEnum.UNREGISTER;
import static com.comleader.operator.common.util.DesensitizeEntityUtil.desensitizePersonalUser;
import static com.comleader.operator.pojo.entity.table.PersonalUserTableDef.PERSONAL_USER;
import static com.comleader.operator.validate.CommonValidator.*;
import static com.comleader.operator.validate.PersonalUserValidator.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.comleader.operator.common.constant.GlobalVariables;
import com.comleader.operator.common.enums.OperatorInspectTypeEnum;
import com.comleader.operator.common.util.ExcelUtil;
import com.comleader.operator.common.util.OperatorObjectUtil;
import com.comleader.operator.core.exception.BusinessException;
import com.comleader.operator.pojo.dto.PersonalUserStatDTO;
import com.comleader.operator.pojo.entity.InspectRecordEntity;
import com.comleader.operator.pojo.entity.InspectReportEntity;
import com.comleader.operator.pojo.entity.PersonalUserEntity;
import com.comleader.operator.service.InspectRecordService;
import com.comleader.operator.service.InspectReportService;
import com.comleader.operator.service.OperatorInspectService;
import com.comleader.operator.service.PersonalUserService;
import com.comleader.operator.validate.PersonalUserValidator;
import com.comleader.operator.validate.ValidateRule;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Dscription
 * @Author 连新景
 * @Date 2024/07/29 16:49
 */
@AllArgsConstructor
@Slf4j
@Service
public class PersonalUserInspect implements InspectStartegy {

    private final InspectRecordService inspectRecordService;

    private final InspectReportService inspectReportService;

    private final PersonalUserService personalUserService;

    private final OperatorInspectService operatorInspectService;

    // 公共规则列表
    private static final List<ValidateRule<PersonalUserEntity>> commonRuleList = new ArrayList<>();
    // 个人移动规则列表
    private static final List<ValidateRule<PersonalUserEntity>> personalMobileRuleList = new ArrayList<>();
    // 个人固话规则列表
    private static final List<ValidateRule<PersonalUserEntity>> personalTelephoneRuleList = new ArrayList<>();
    // 单位移动规则列表
    private static final List<ValidateRule<PersonalUserEntity>> companyMobileRuleList = new ArrayList<>();
    // 单位固话规则列表
    private static final List<ValidateRule<PersonalUserEntity>> companyTelephoneRuleList = new ArrayList<>();
    // 行业移动规则列表
    private static final List<ValidateRule<PersonalUserEntity>> industryMobileRuleList = new ArrayList<>();
    // 行业固话规则列表
    private static final List<ValidateRule<PersonalUserEntity>> industryTelephoneRuleList = new ArrayList<>();

    @PostConstruct
    public void init() {
        commonRuleList.add(new ValidateRule<>("101", "格式异常数据", PersonalUserValidator::isFormatException, null));
        // 字段异常单独校验，因为缺失字段无法映射到对象上
        // validateRuleList.add(new ValidateRule<>("102", "字段异常数据", null));
        commonRuleList.add(new ValidateRule<>("103", "不在网状态", data -> !isDictIncorrect(PERSONAL_NOT_NET_STATE, data.getNumberStatus()), null));
        commonRuleList
            .add(new ValidateRule<>("104", "非实名停机", data -> StrUtil.isNotBlank(data.getNumberStatus()) && data.getNumberStatus().contains("非实名停机"), null));

        personalMobileRuleList.add(new ValidateRule<>("105", "个人移动用户-机主证件类型未登记", data -> isUnregister(data.getOwnerIdType()), UNREGISTER));
        personalMobileRuleList.add(new ValidateRule<>("106", "个人移动用户-机主姓名未登记", data -> isUnregister(data.getOwnerName()), UNREGISTER));
        personalMobileRuleList.add(new ValidateRule<>("107", "个人移动用户-机主证件号码未登记", data -> isUnregister(data.getOwnerIdNumber()), UNREGISTER));
        personalMobileRuleList.add(new ValidateRule<>("108", "个人移动用户-机主证件地址未登记", data -> isUnregister(data.getOwnerIdAddress()), UNREGISTER));
        personalMobileRuleList.add(new ValidateRule<>("109", "个人移动用户-机主姓名&证件号码未登记", data -> isUnregister(data.getOwnerName(), data.getOwnerIdNumber()), null));
        personalMobileRuleList.add(new ValidateRule<>("110", "个人移动用户-机主姓名&证件地址未登记", data -> isUnregister(data.getOwnerName(), data.getOwnerIdAddress()), null));
        personalMobileRuleList
            .add(new ValidateRule<>("111", "个人移动用户-机主证件号码&证件地址未登记", data -> isUnregister(data.getOwnerIdNumber(), data.getOwnerIdAddress()), null));
        personalMobileRuleList.add(new ValidateRule<>("112", "个人移动用户-机主姓名&证件号码&证件地址未登记",
            data -> isUnregister(data.getOwnerName(), data.getOwnerIdNumber(), data.getOwnerIdAddress()), null));
        personalMobileRuleList.add(new ValidateRule<>("113", "个人移动用户-经办人信息未登记", PersonalUserValidator::isPersonalAgentUnregister, UNREGISTER));
        personalMobileRuleList
            .add(new ValidateRule<>("114", "个人移动用户-证件类型校验不合规", data -> isIdTypeNoncompliant(PERSONAL_IDCARD_TYPE, data.getOwnerIdType()), NONCOMPLIANT));
        personalMobileRuleList.add(new ValidateRule<>("115", "个人移动用户-机主姓名校验不合规", data -> isNameNoncompliant(data.getOwnerName()), NONCOMPLIANT));
        personalMobileRuleList
            .add(new ValidateRule<>("116", "个人移动用户-机主证件号码校验不合规", data -> isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()), NONCOMPLIANT));
        personalMobileRuleList.add(new ValidateRule<>("117", "个人移动用户-机主证件地址校验不合规", data -> isAddressNoncompliant(data.getOwnerIdAddress()), NONCOMPLIANT));
        personalMobileRuleList.add(new ValidateRule<>("118", "个人移动用户-机主姓名&证件号码校验不合规",
            data -> isNameNoncompliant(data.getOwnerName()) && isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()), null));
        personalMobileRuleList.add(new ValidateRule<>("119", "个人移动用户-机主姓名&证件地址校验不合规",
            data -> isNameNoncompliant(data.getOwnerName()) && isAddressNoncompliant(data.getOwnerIdAddress()), null));
        personalMobileRuleList.add(new ValidateRule<>("120", "个人移动用户-机主证件号码&证件地址校验不合规",
            data -> isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()) && isAddressNoncompliant(data.getOwnerIdAddress()), null));
        personalMobileRuleList.add(new ValidateRule<>("121", "个人移动用户-机主姓名&证件号码&证件地址校验不合规", data -> isNameNoncompliant(data.getOwnerName())
            && isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()) && isAddressNoncompliant(data.getOwnerIdAddress()), null));
        personalMobileRuleList.add(new ValidateRule<>("122", "个人移动用户-经办人信息校验不合规", PersonalUserValidator::isPersonalAgentNoncompliant, NONCOMPLIANT));

        personalTelephoneRuleList.add(new ValidateRule<>("123", "个人固话用户-机主证件类型未登记", data -> isUnregister(data.getOwnerIdType()), UNREGISTER));
        personalTelephoneRuleList.add(new ValidateRule<>("124", "个人固话用户-机主姓名未登记", data -> isUnregister(data.getOwnerName()), UNREGISTER));
        personalTelephoneRuleList.add(new ValidateRule<>("125", "个人固话用户-机主证件号码未登记", data -> isUnregister(data.getOwnerIdNumber()), UNREGISTER));
        personalTelephoneRuleList.add(new ValidateRule<>("126", "个人固话用户-机主证件地址未登记", data -> isUnregister(data.getOwnerIdAddress()), UNREGISTER));
        personalTelephoneRuleList
            .add(new ValidateRule<>("127", "个人固话用户-机主姓名&证件号码未登记", data -> isUnregister(data.getOwnerName(), data.getOwnerIdNumber()), null));
        personalTelephoneRuleList
            .add(new ValidateRule<>("128", "个人固话用户-机主姓名&证件地址未登记", data -> isUnregister(data.getOwnerName(), data.getOwnerIdAddress()), null));
        personalTelephoneRuleList
            .add(new ValidateRule<>("129", "个人固话用户-机主证件号码&证件地址未登记", data -> isUnregister(data.getOwnerIdNumber(), data.getOwnerIdAddress()), null));
        personalTelephoneRuleList.add(new ValidateRule<>("130", "个人固话用户-机主姓名&证件号码&证件地址未登记",
            data -> isUnregister(data.getOwnerName(), data.getOwnerIdNumber(), data.getOwnerIdAddress()), null));
        personalTelephoneRuleList.add(new ValidateRule<>("131", "个人固话用户-经办人信息未登记", PersonalUserValidator::isPersonalAgentUnregister, UNREGISTER));
        personalTelephoneRuleList
            .add(new ValidateRule<>("132", "个人固话用户-机主证件类型校验不合规", data -> isIdTypeNoncompliant(PERSONAL_IDCARD_TYPE, data.getOwnerIdType()), NONCOMPLIANT));
        personalTelephoneRuleList.add(new ValidateRule<>("133", "个人固话用户-机主姓名校验不合规", data -> isNameNoncompliant(data.getOwnerName()), NONCOMPLIANT));
        personalTelephoneRuleList
            .add(new ValidateRule<>("134", "个人固话用户-证件号码校验不合规", data -> isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()), NONCOMPLIANT));
        personalTelephoneRuleList.add(new ValidateRule<>("135", "个人固话用户-机主证件地址校验不合规", data -> isAddressNoncompliant(data.getOwnerIdAddress()), NONCOMPLIANT));
        personalTelephoneRuleList.add(new ValidateRule<>("136", "个人固话用户-用户姓名&证件号码校验不合规",
            data -> isNameNoncompliant(data.getOwnerName()) && isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()), null));
        personalTelephoneRuleList.add(new ValidateRule<>("137", "个人固话用户-用户姓名&证件地址校验不合规",
            data -> isNameNoncompliant(data.getOwnerName()) && isAddressNoncompliant(data.getOwnerIdAddress()), null));
        personalTelephoneRuleList.add(new ValidateRule<>("138", "个人固话用户-证件号码&证件地址校验不合规",
            data -> isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()) && isAddressNoncompliant(data.getOwnerIdAddress()), null));
        personalTelephoneRuleList.add(new ValidateRule<>("139", "个人固话用户-用户姓名&证件号码&证件地址校验不合规", data -> isNameNoncompliant(data.getOwnerName())
            && isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()) && isAddressNoncompliant(data.getOwnerIdAddress()), null));
        personalTelephoneRuleList.add(new ValidateRule<>("140", "个人固话用户-经办人信息校验不合规", PersonalUserValidator::isPersonalAgentNoncompliant, NONCOMPLIANT));

        companyMobileRuleList.add(new ValidateRule<>("141", "单位移动用户-使用人信息未登记", PersonalUserValidator::isUserUnregister, UNREGISTER));
        companyMobileRuleList.add(new ValidateRule<>("142", "单位移动用户-经办人信息未登记", PersonalUserValidator::isAgentUnregister, UNREGISTER));
        companyMobileRuleList.add(new ValidateRule<>("143", "单位移动用户-单位信息未登记", PersonalUserValidator::isCompanyUnregister, UNREGISTER));
        companyMobileRuleList.add(new ValidateRule<>("144", "单位移动用户-使用人&经办人信息未登记", data -> isUserUnregister(data) && isAgentUnregister(data), null));
        companyMobileRuleList.add(new ValidateRule<>("145", "单位移动用户-使用人&单位信息未登记", data -> isUserUnregister(data) && isCompanyUnregister(data), null));
        companyMobileRuleList.add(new ValidateRule<>("146", "单位移动用户-经办人&单位信息未登记", data -> isAgentUnregister(data) && isCompanyUnregister(data), null));
        companyMobileRuleList.add(
            new ValidateRule<>("147", "单位移动用户-使用人&经办人&单位信息未登记", data -> isUserUnregister(data) && isAgentUnregister(data) && isCompanyUnregister(data), null));
        companyMobileRuleList.add(new ValidateRule<>("148", "单位移动用户-使用人信息校验不合规", PersonalUserValidator::isUserNoncompliant, NONCOMPLIANT));
        companyMobileRuleList.add(new ValidateRule<>("149", "单位移动用户-经办人信息校验不合规", PersonalUserValidator::isAgentNoncompliant, NONCOMPLIANT));
        companyMobileRuleList.add(new ValidateRule<>("150", "单位移动用户-单位信息校验不合规", PersonalUserValidator::isCompanyNoncompliant, NONCOMPLIANT));
        companyMobileRuleList
            .add(new ValidateRule<>("151", "单位移动用户-机主信息（使用人信息）&经办人信息校验不合规", data -> isUserNoncompliant(data) && isAgentNoncompliant(data), null));
        companyMobileRuleList
            .add(new ValidateRule<>("152", "单位移动用户-机主信息（使用人信息）&单位信息校验不合规", data -> isUserNoncompliant(data) && isCompanyNoncompliant(data), null));
        companyMobileRuleList.add(new ValidateRule<>("153", "单位移动用户-经办人&单位信息校验不合规", data -> isAgentNoncompliant(data) && isCompanyNoncompliant(data), null));
        companyMobileRuleList.add(new ValidateRule<>("154", "单位移动用户-使用人&经办人&单位信息校验不合规",
            data -> isUserNoncompliant(data) && isAgentNoncompliant(data) && isCompanyNoncompliant(data), null));

        companyTelephoneRuleList.add(new ValidateRule<>("155", "单位固话用户-经办人信息未登记", PersonalUserValidator::isAgentUnregister, UNREGISTER));
        companyTelephoneRuleList.add(new ValidateRule<>("156", "单位固话用户-单位信息未登记", PersonalUserValidator::isCompanyUnregister, UNREGISTER));
        companyTelephoneRuleList.add(new ValidateRule<>("157", "单位固话用户-经办人&单位信息未登记", data -> isAgentUnregister(data) && isCompanyUnregister(data), null));
        companyTelephoneRuleList.add(new ValidateRule<>("158", "单位固话用户-经办人信息校验不合规", PersonalUserValidator::isAgentNoncompliant, NONCOMPLIANT));
        companyTelephoneRuleList.add(new ValidateRule<>("159", "单位固话用户-单位信息校验不合规", PersonalUserValidator::isCompanyNoncompliant, NONCOMPLIANT));
        companyTelephoneRuleList.add(new ValidateRule<>("160", "单位固话用户-经办人&单位信息校验不合规", data -> isAgentNoncompliant(data) && isCompanyNoncompliant(data), null));

        industryMobileRuleList.add(new ValidateRule<>("161", "行业移动应用-经办人信息未登记", PersonalUserValidator::isAgentUnregister, UNREGISTER));
        industryMobileRuleList.add(new ValidateRule<>("162", "行业移动应用-单位信息未登记", PersonalUserValidator::isCompanyUnregister, UNREGISTER));
        industryMobileRuleList.add(new ValidateRule<>("163", "行业移动应用-责任人信息未登记", PersonalUserValidator::isIndustryUserPicUnregister, UNREGISTER));
        industryMobileRuleList.add(new ValidateRule<>("164", "行业移动应用-经办人&单位信息未登记", data -> isAgentUnregister(data) && isCompanyUnregister(data), null));
        industryMobileRuleList
            .add(new ValidateRule<>("165", "行业移动应用-责任人&经办人信息未登记", data -> isIndustryUserPicUnregister(data) && isAgentUnregister(data), null));
        industryMobileRuleList
            .add(new ValidateRule<>("166", "行业移动应用-责任人&单位信息未登记", data -> isIndustryUserPicUnregister(data) && isCompanyUnregister(data), null));
        industryMobileRuleList.add(new ValidateRule<>("167", "行业移动应用-责任人&经办人&单位信息未登记",
            data -> isIndustryUserPicUnregister(data) && isAgentUnregister(data) && isCompanyUnregister(data), null));
        industryMobileRuleList.add(new ValidateRule<>("168", "行业移动应用-经办人信息校验不合规", PersonalUserValidator::isAgentNoncompliant, NONCOMPLIANT));
        industryMobileRuleList.add(new ValidateRule<>("169", "行业移动应用-单位信息校验不合规", PersonalUserValidator::isCompanyNoncompliant, NONCOMPLIANT));
        industryMobileRuleList.add(new ValidateRule<>("170", "行业移动应用-责任人信息校验不合规", PersonalUserValidator::isIndustryUserPicNoncompliant, NONCOMPLIANT));
        industryMobileRuleList.add(new ValidateRule<>("171", "行业移动应用-经办人&单位信息校验不合规", data -> isAgentNoncompliant(data) && isCompanyNoncompliant(data), null));
        industryMobileRuleList
            .add(new ValidateRule<>("172", "行业移动应用-责任人&经办人信息校验不合规", data -> isIndustryUserPicNoncompliant(data) && isAgentNoncompliant(data), null));
        industryMobileRuleList.add(new ValidateRule<>("173", "行业移动应用-责任人&经办人&单位信息校验不合规",
            data -> isIndustryUserPicNoncompliant(data) && isAgentNoncompliant(data) && isCompanyNoncompliant(data), null));
        industryMobileRuleList
            .add(new ValidateRule<>("174", "行业移动应用-责任人&单位信息校验不合规", data -> isIndustryUserPicNoncompliant(data) && isCompanyNoncompliant(data), null));

        industryTelephoneRuleList.add(new ValidateRule<>("175", "行业固话应用-经办人信息未登记", PersonalUserValidator::isAgentUnregister, UNREGISTER));
        industryTelephoneRuleList.add(new ValidateRule<>("176", "行业固话应用-单位信息未登记", PersonalUserValidator::isCompanyUnregister, UNREGISTER));
        industryTelephoneRuleList.add(new ValidateRule<>("177", "行业固话应用-责任人信息未登记", PersonalUserValidator::isIndustryUserPicUnregister, UNREGISTER));
        industryTelephoneRuleList.add(new ValidateRule<>("178", "行业固话应用-经办人&单位信息未登记", data -> isAgentUnregister(data) && isCompanyUnregister(data), null));
        industryTelephoneRuleList
            .add(new ValidateRule<>("179", "行业固话应用-经办人&责任人信息未登记", data -> isIndustryUserPicUnregister(data) && isAgentUnregister(data), null));
        industryTelephoneRuleList
            .add(new ValidateRule<>("180", "行业固话应用-责任人&单位信息未登记", data -> isIndustryUserPicUnregister(data) && isCompanyUnregister(data), null));
        industryTelephoneRuleList.add(new ValidateRule<>("181", "行业固话应用-经办人&责任人&单位信息未登记",
            data -> isIndustryUserPicUnregister(data) && isAgentUnregister(data) && isCompanyUnregister(data), null));
        industryTelephoneRuleList.add(new ValidateRule<>("182", "行业固话应用-经办人信息校验不合规", PersonalUserValidator::isAgentNoncompliant, NONCOMPLIANT));
        industryTelephoneRuleList.add(new ValidateRule<>("183", "行业固话应用-单位信息校验不合规", PersonalUserValidator::isCompanyNoncompliant, NONCOMPLIANT));
        industryTelephoneRuleList.add(new ValidateRule<>("184", "行业固话应用-责任人信息校验不合规", PersonalUserValidator::isIndustryUserPicNoncompliant, NONCOMPLIANT));
        industryTelephoneRuleList
            .add(new ValidateRule<>("185", "行业固话应用-经办人&单位信息校验不合规", data -> isAgentNoncompliant(data) && isCompanyNoncompliant(data), null));
        industryTelephoneRuleList
            .add(new ValidateRule<>("186", "行业固话应用-经办人&责任人信息校验不合规", data -> isIndustryUserPicNoncompliant(data) && isAgentNoncompliant(data), null));
        industryTelephoneRuleList
            .add(new ValidateRule<>("187", "行业固话应用-责任人&单位信息校验不合规", data -> isIndustryUserPicNoncompliant(data) && isCompanyNoncompliant(data), null));
        industryTelephoneRuleList.add(new ValidateRule<>("188", "行业固话应用-经办人&责任人&单位信息校验不合规",
            data -> isIndustryUserPicNoncompliant(data) && isAgentNoncompliant(data) && isCompanyNoncompliant(data), null));
    }

    @Override
    public void inspect(InspectRecordEntity inspectRecord, String importFilePath) {
        int inspectRecordId = inspectRecord.getId();
        String reportFileDir = inspectRecord.getReportFileDir();
        try {
            List<ValidateRule<PersonalUserEntity>> enableCommonRules = listEnableValidateRule(commonRuleList, OperatorInspectTypeEnum.PERSONAL_USER);
            List<ValidateRule<PersonalUserEntity>> enablePersonalMobileRules =
                listEnableValidateRule(personalMobileRuleList, OperatorInspectTypeEnum.PERSONAL_USER);
            List<ValidateRule<PersonalUserEntity>> enablePersonalTelephoneRules =
                listEnableValidateRule(personalTelephoneRuleList, OperatorInspectTypeEnum.PERSONAL_USER);
            List<ValidateRule<PersonalUserEntity>> enableCompanyMobileRules =
                listEnableValidateRule(companyMobileRuleList, OperatorInspectTypeEnum.PERSONAL_USER);
            List<ValidateRule<PersonalUserEntity>> enableCompanyTelephoneRules =
                listEnableValidateRule(companyTelephoneRuleList, OperatorInspectTypeEnum.PERSONAL_USER);
            List<ValidateRule<PersonalUserEntity>> enableIndustryMobileRules =
                listEnableValidateRule(industryMobileRuleList, OperatorInspectTypeEnum.PERSONAL_USER);
            List<ValidateRule<PersonalUserEntity>> enableIndustryTelephoneRules =
                listEnableValidateRule(industryTelephoneRuleList, OperatorInspectTypeEnum.PERSONAL_USER);
            BufferedReader reader = null;
            String line;
            List<String> filedList;
            List<String> fieldExceptionList = new ArrayList<>();
            Map<String, List<PersonalUserEntity>> codeEntityMap = new TreeMap<>();
            // 总量
            int totalNum = 0;
            PersonalUserStatDTO personalUserStatDTO = new PersonalUserStatDTO();
            try {
                reader = FileUtil.getReader(new File(importFilePath), CHARSET_GBK);
                while (true) {
                    line = reader.readLine();
                    if (StrUtil.isBlank(line)) {
                        break;
                    }
                    totalNum++;
                    filedList = StrUtil.split(line, "||");
                    if (filedList.size() != PERSONAL_USER_FIELD_NUM) {
                        fieldExceptionList.add(line);
                        continue;
                    }
                    // 未登记标识
                    boolean unregisterFlag = false;
                    // 不合规标识
                    boolean noncomplaianceFlag = false;
                    // 公共校验规则标识
                    boolean commonRuleComplianceFlag = true;
                    // 个人移动用户合规标识
                    boolean personalMobileComplianceFlag = true;
                    // 单位移动用户-合规标识
                    boolean companyMobileComplianceFlag = true;
                    // 个人固话用户-合规标识
                    boolean personalTelephoneComplianceFlag = true;
                    // 单位固话用户-合规标识
                    boolean companyTelephoneComplianceFlag = true;
                    // 行业移动应用-合规标识
                    boolean industryMobileComplianceFlag = true;
                    // 行业固话应用-合规标识
                    boolean industryTelephoneComplianceFlag = true;
                    PersonalUserEntity personalUser = OperatorObjectUtil.createObj(filedList, PersonalUserEntity.class);
                    // 公共校验规则
                    for (ValidateRule<PersonalUserEntity> validateRule : enableCommonRules) {
                        if (validateRule.getValidate().test(personalUser)) {
                            commonRuleComplianceFlag = false;
                            codeEntityMap.computeIfAbsent(validateRule.getRuleCode(), key -> ListUtil.list(false)).add(personalUser);
                        }
                    }

                    if (PERSON_USER.equals(personalUser.getCustomerType()) && MOBILE_PHONE.equals(personalUser.getUserBusinessType())) {
                        for (ValidateRule<PersonalUserEntity> validateRule : enablePersonalMobileRules) {
                            if (validateRule.getValidate().test(personalUser)) {
                                codeEntityMap.computeIfAbsent(validateRule.getRuleCode(), key -> ListUtil.list(false)).add(personalUser);
                                // 只要有一个匹配上，那就不是合规的
                                personalMobileComplianceFlag = false;
                                if (UNREGISTER == validateRule.getType()) {
                                    unregisterFlag = true;
                                } else if (NONCOMPLIANT == validateRule.getType()) {
                                    noncomplaianceFlag = true;
                                }
                            }
                        }
                    } else if (PERSON_USER.equals(personalUser.getCustomerType()) && TELEPHONE.equals(personalUser.getUserBusinessType())) {
                        for (ValidateRule<PersonalUserEntity> validateRule : enablePersonalTelephoneRules) {
                            if (validateRule.getValidate().test(personalUser)) {
                                codeEntityMap.computeIfAbsent(validateRule.getRuleCode(), key -> ListUtil.list(false)).add(personalUser);
                                // 只要有一个匹配上，那就不是合规的
                                personalTelephoneComplianceFlag = false;
                                if (UNREGISTER == validateRule.getType()) {
                                    unregisterFlag = true;
                                } else if (NONCOMPLIANT == validateRule.getType()) {
                                    noncomplaianceFlag = true;
                                }
                            }
                        }
                    } else if (COMPANY_USER.equals(personalUser.getCustomerType()) && MOBILE_PHONE.equals(personalUser.getUserBusinessType())) {
                        for (ValidateRule<PersonalUserEntity> validateRule : enableCompanyMobileRules) {
                            if (validateRule.getValidate().test(personalUser)) {
                                codeEntityMap.computeIfAbsent(validateRule.getRuleCode(), key -> ListUtil.list(false)).add(personalUser);
                                // 只要有一个匹配上，那就不是合规的
                                companyMobileComplianceFlag = false;
                                if (UNREGISTER == validateRule.getType()) {
                                    unregisterFlag = true;
                                } else if (NONCOMPLIANT == validateRule.getType()) {
                                    noncomplaianceFlag = true;
                                }
                            }
                        }
                    } else if (COMPANY_USER.equals(personalUser.getCustomerType()) && TELEPHONE.equals(personalUser.getUserBusinessType())) {
                        for (ValidateRule<PersonalUserEntity> validateRule : enableCompanyTelephoneRules) {
                            if (validateRule.getValidate().test(personalUser)) {
                                codeEntityMap.computeIfAbsent(validateRule.getRuleCode(), key -> ListUtil.list(false)).add(personalUser);
                                // 只要有一个匹配上，那就不是合规的
                                companyTelephoneComplianceFlag = false;
                                if (UNREGISTER == validateRule.getType()) {
                                    unregisterFlag = true;
                                } else if (NONCOMPLIANT == validateRule.getType()) {
                                    noncomplaianceFlag = true;
                                }
                            }
                        }
                    } else if (INDUSTRY_USER.equals(personalUser.getCustomerType()) && MOBILE_PHONE.equals(personalUser.getUserBusinessType())) {
                        for (ValidateRule<PersonalUserEntity> validateRule : enableIndustryMobileRules) {
                            if (validateRule.getValidate().test(personalUser)) {
                                codeEntityMap.computeIfAbsent(validateRule.getRuleCode(), key -> ListUtil.list(false)).add(personalUser);
                                // 只要有一个匹配上，那就不是合规的
                                industryMobileComplianceFlag = false;
                                if (UNREGISTER == validateRule.getType()) {
                                    unregisterFlag = true;
                                } else if (NONCOMPLIANT == validateRule.getType()) {
                                    noncomplaianceFlag = true;
                                }
                            }
                        }
                    } else if (INDUSTRY_USER.equals(personalUser.getCustomerType()) && TELEPHONE.equals(personalUser.getUserBusinessType())) {
                        for (ValidateRule<PersonalUserEntity> validateRule : enableIndustryTelephoneRules) {
                            if (validateRule.getValidate().test(personalUser)) {
                                codeEntityMap.computeIfAbsent(validateRule.getRuleCode(), key -> ListUtil.list(false)).add(personalUser);
                                // 只要有一个匹配上，那就不是合规的
                                industryTelephoneComplianceFlag = false;
                                if (UNREGISTER == validateRule.getType()) {
                                    unregisterFlag = true;
                                } else if (NONCOMPLIANT == validateRule.getType()) {
                                    noncomplaianceFlag = true;
                                }
                            }
                        }
                    }
                    // 只要是未登记或者不合规，那么肯定不属于合规了，因为合规的要求是该类型所有的不合规项都匹配不上
                    if (unregisterFlag || noncomplaianceFlag) {
                        if (unregisterFlag) {
                            personalUserStatDTO.getUnregisterList().add(personalUser);
                        }
                        if (noncomplaianceFlag) {
                            personalUserStatDTO.getNoncompliantList().add(personalUser);
                        }
                    } else {
                        // 通用校验规则必须也为true，才有合规的可能性
                        if (commonRuleComplianceFlag) {
                            if (PERSON_USER.equals(personalUser.getCustomerType()) && MOBILE_PHONE.equals(personalUser.getUserBusinessType())
                                && personalMobileComplianceFlag) {
                                personalUserStatDTO.getPersonalMobileList().add(personalUser);
                            } else if (PERSON_USER.equals(personalUser.getCustomerType()) && TELEPHONE.equals(personalUser.getUserBusinessType())
                                && personalTelephoneComplianceFlag) {
                                personalUserStatDTO.getPersonalTelephoneList().add(personalUser);
                            } else if (COMPANY_USER.equals(personalUser.getCustomerType()) && MOBILE_PHONE.equals(personalUser.getUserBusinessType())
                                && companyMobileComplianceFlag) {
                                personalUserStatDTO.getCompanyMobileList().add(personalUser);
                            } else if (COMPANY_USER.equals(personalUser.getCustomerType()) && TELEPHONE.equals(personalUser.getUserBusinessType())
                                && companyTelephoneComplianceFlag) {
                                personalUserStatDTO.getCompanyTelephoneList().add(personalUser);
                            } else if (INDUSTRY_USER.equals(personalUser.getCustomerType()) && MOBILE_PHONE.equals(personalUser.getUserBusinessType())
                                && industryMobileComplianceFlag) {
                                personalUserStatDTO.getIndustryMobileList().add(personalUser);
                            } else if (INDUSTRY_USER.equals(personalUser.getCustomerType()) && TELEPHONE.equals(personalUser.getUserBusinessType())
                                && industryTelephoneComplianceFlag) {
                                personalUserStatDTO.getIndustryTelephoneList().add(personalUser);
                            }
                        }
                    }
                }
            } catch (IOException exception) {
                log.error("个人用户实名制检查失败，读取文件内容异常", exception);
                operatorInspectService.deleteImportData(OperatorInspectTypeEnum.PERSONAL_USER.getType(), inspectRecord.getImportRecordId());
                inspectRecordService.updateStatusAndFinishTime(inspectRecordId, FAILED);
                throw exception;
            } finally {
                IoUtil.close(reader);
            }
            // 启用的校验规则code
            List<String> enableCodeList = GlobalVariables.getTypeCodeMap().get(OperatorInspectTypeEnum.PERSONAL_USER.getType());
            Map<String, String> codeNameMap = GlobalVariables.getCodeNameMap();
            List<InspectReportEntity> inspectReportList = new ArrayList<>();
            // 统计map
            Map<String, Integer> statisticsMap = new LinkedHashMap<>();
            statisticsMap.put("检查总量", totalNum);
            if (enableCodeList.contains(PERSONAL_FORMAT_EXCEPTION_CODE)) {
                statisticsMap.put("格式异常数据量",
                    !codeEntityMap.containsKey(PERSONAL_FORMAT_EXCEPTION_CODE) ? 0 : codeEntityMap.get(PERSONAL_FORMAT_EXCEPTION_CODE).size());
            }
            // 是否校验字段异常
            if (enableCodeList.contains(PERSONAL_FIELD_EXCEPTION_CODE)) {
                statisticsMap.put("字段异常数据量", fieldExceptionList.size());
                if (CollUtil.isNotEmpty(fieldExceptionList)) {
                    String fileName = codeNameMap.getOrDefault(PERSONAL_FIELD_EXCEPTION_CODE, "字段异常数据") + ".txt";
                    // 完整路径为./reportFile/yyyyMMddHHmmss/字段异常数据.txt
                    FileUtil.writeUtf8Lines(fieldExceptionList, new File(reportFileDir + fileName));
                    InspectReportEntity inspectReportEntity =
                        InspectReportEntity.builder().fileName(fileName).recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
                    inspectReportList.add(inspectReportEntity);
                }
            }
            statisticsMap.put("未登记总量", personalUserStatDTO.getUnregisterList().size());
            statisticsMap.put("不合规总量", personalUserStatDTO.getNoncompliantList().size());
            statisticsMap.put("全量合规量", personalUserStatDTO.getCompliantList().size());
            statisticsMap.put("个人移动用户-合规量", personalUserStatDTO.getPersonalMobileList().size());
            statisticsMap.put("单位移动用户-合规量", personalUserStatDTO.getCompanyMobileList().size());
            statisticsMap.put("个人固话用户-合规量", personalUserStatDTO.getPersonalTelephoneList().size());
            statisticsMap.put("单位固话用户-合规量", personalUserStatDTO.getCompanyTelephoneList().size());
            statisticsMap.put("行业移动应用-合规量", personalUserStatDTO.getIndustryMobileList().size());
            statisticsMap.put("行业固话应用-合规量", personalUserStatDTO.getIndustryTelephoneList().size());
            handleMultipleNamesData(enableCodeList, codeEntityMap);
            // 遍历启用的校验规则
            enableCodeList.forEach(ruleCode -> {
                // 格式异常、字段异常上边已经处理过了
                if (PERSONAL_FORMAT_EXCEPTION_CODE.equals(ruleCode) || PERSONAL_FIELD_EXCEPTION_CODE.equals(ruleCode)) {
                    return;
                }
                // 如果codeEntityMap没有该校验规则code，表示该校验规则虽然启用了但是没有符合条件的数据，
                if (!codeEntityMap.containsKey(ruleCode)) {
                    statisticsMap.put(codeNameMap.get(ruleCode), 0);
                } else {
                    statisticsMap.put(codeNameMap.get(ruleCode), codeEntityMap.get(ruleCode).size());
                }
            });
            genreateFixedTermsExcel(statisticsMap, reportFileDir, inspectRecordId, inspectReportList, personalUserStatDTO);
            // 开始循环生成excel文件
            codeEntityMap.forEach((key, value) -> {
                if (CollectionUtil.isEmpty(value)) {
                    return;
                }
                // 完整路径为./reportFile/yyyyMMddHHmmss/校验规则名称.xlsx
                String fileName = codeNameMap.get(key) + ExcelTypeEnum.XLSX.getValue();
                String fullPath = reportFileDir + fileName;
                desensitizePersonalUser(value);
                ExcelUtil.writeMultipleSheet(fullPath, PersonalUserEntity.class, codeNameMap.get(key), value);
                inspectReportList.add(InspectReportEntity.builder().fileName(fileName).recordId(inspectRecordId).generateTime(LocalDateTime.now()).build());
            });
            inspectReportService.saveBatch(inspectReportList);
        } catch (Exception exception) {
            log.error("个人用户实名制检查失败", exception);
            operatorInspectService.deleteImportData(OperatorInspectTypeEnum.PERSONAL_USER.getType(), inspectRecord.getImportRecordId());
            FileUtil.del(new File(reportFileDir));
            inspectRecordService.updateStatusAndFinishTime(inspectRecordId, FAILED);
            throw new BusinessException(exception);
        }
    }

    /**
     * @Description 生成固定项excel文件
     * @Auhtor 连新景
     * @Date 2024/08/13 17:41
     * @param statisticsMap
     * @param reportFileDir
     * @param inspectRecordId
     * @param inspectReportList
     * @param personalUserStatDTO
     */
    private void genreateFixedTermsExcel(Map<String, Integer> statisticsMap, String reportFileDir, Integer inspectRecordId,
        List<InspectReportEntity> inspectReportList, PersonalUserStatDTO personalUserStatDTO) {
        // 生成检查统计表
        List<List<Object>> statisticsList = new ArrayList<>(statisticsMap.size());
        statisticsMap.forEach((key, value) -> {
            List<Object> data = new ArrayList<>(2);
            data.add(key);
            data.add(value);
            statisticsList.add(data);
        });
        EasyExcel.write(reportFileDir + "检查统计表.xlsx").registerWriteHandler(new InspectStatColumnWidthStyleStrategy()).sheet("检查统计表").doWrite(statisticsList);
        InspectReportEntity inspectReportEntity =
            InspectReportEntity.builder().fileName("检查统计表.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
        inspectReportList.add(inspectReportEntity);
        // 生成固定明细项
        if (CollectionUtil.isNotEmpty(personalUserStatDTO.getUnregisterList())) {
            desensitizePersonalUser(personalUserStatDTO.getUnregisterList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "未登记数据.xlsx", PersonalUserEntity.class, "未登记数据", personalUserStatDTO.getUnregisterList());
            inspectReportEntity = InspectReportEntity.builder().fileName("未登记数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(personalUserStatDTO.getNoncompliantList())) {
            desensitizePersonalUser(personalUserStatDTO.getNoncompliantList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "不合规数据.xlsx", PersonalUserEntity.class, "不合规数据", personalUserStatDTO.getNoncompliantList());
            inspectReportEntity = InspectReportEntity.builder().fileName("不合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(personalUserStatDTO.getCompliantList())) {
            desensitizePersonalUser(personalUserStatDTO.getCompliantList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "全量合规数据.xlsx", PersonalUserEntity.class, "全量合规数据", personalUserStatDTO.getCompliantList());
            inspectReportEntity = InspectReportEntity.builder().fileName("全量合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(personalUserStatDTO.getPersonalMobileList())) {
            desensitizePersonalUser(personalUserStatDTO.getPersonalMobileList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "个人移动用户-合规数据.xlsx", PersonalUserEntity.class, "个人移动用户-合规数据",
                personalUserStatDTO.getPersonalMobileList());
            inspectReportEntity =
                InspectReportEntity.builder().fileName("个人移动用户-合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(personalUserStatDTO.getCompanyMobileList())) {
            desensitizePersonalUser(personalUserStatDTO.getCompanyMobileList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "单位移动用户-合规数据.xlsx", PersonalUserEntity.class, "单位移动用户-合规数据",
                personalUserStatDTO.getCompanyMobileList());
            inspectReportEntity =
                InspectReportEntity.builder().fileName("单位移动用户-合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(personalUserStatDTO.getPersonalTelephoneList())) {
            desensitizePersonalUser(personalUserStatDTO.getPersonalTelephoneList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "个人固话用户-合规数据.xlsx", PersonalUserEntity.class, "个人固话用户-合规数据",
                personalUserStatDTO.getPersonalTelephoneList());
            inspectReportEntity =
                InspectReportEntity.builder().fileName("个人固话用户-合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(personalUserStatDTO.getCompanyTelephoneList())) {
            desensitizePersonalUser(personalUserStatDTO.getCompanyTelephoneList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "单位固话用户-合规数据.xlsx", PersonalUserEntity.class, "单位固话用户-合规数据",
                personalUserStatDTO.getCompanyTelephoneList());
            inspectReportEntity =
                InspectReportEntity.builder().fileName("单位固话用户-合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(personalUserStatDTO.getIndustryMobileList())) {
            desensitizePersonalUser(personalUserStatDTO.getIndustryMobileList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "行业移动应用-合规数据.xlsx", PersonalUserEntity.class, "行业移动应用-合规数据",
                personalUserStatDTO.getIndustryMobileList());
            inspectReportEntity =
                InspectReportEntity.builder().fileName("行业移动应用-合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(personalUserStatDTO.getIndustryTelephoneList())) {
            desensitizePersonalUser(personalUserStatDTO.getIndustryTelephoneList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "行业固话应用-合规数据.xlsx", PersonalUserEntity.class, "行业固话应用-合规数据",
                personalUserStatDTO.getIndustryTelephoneList());
            inspectReportEntity =
                InspectReportEntity.builder().fileName("行业固话应用-合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
    }

    /**
     * @Description 处理一证多名数据
     * @Auhtor 连新景
     * @Date 2024/08/12 17:26
     * @param enableCodeList
     * @param codeEntityMap
     */
    private void handleMultipleNamesData(List<String> enableCodeList, Map<String, List<PersonalUserEntity>> codeEntityMap) {
        // 个人移动一证多名
        List<PersonalUserEntity> psrsonalMobileList = ListUtil.empty();
        if (enableCodeList.contains("189")) {
            psrsonalMobileList = personalUserService.listByTypeAndName(PERSON_USER, MOBILE_PHONE, PERSONAL_USER.OWNER_ID_NUMBER, PERSONAL_USER.OWNER_NAME);
            codeEntityMap.put("189", psrsonalMobileList);
        }
        // 个人固话一证多名
        List<PersonalUserEntity> personalTelephoneList = ListUtil.empty();
        if (enableCodeList.contains("190")) {
            personalTelephoneList = personalUserService.listByTypeAndName(PERSON_USER, TELEPHONE, PERSONAL_USER.OWNER_ID_NUMBER, PERSONAL_USER.OWNER_NAME);
            codeEntityMap.put("190", personalTelephoneList);
        }
        // 单位移动一证多名
        List<PersonalUserEntity> companyMobileList = ListUtil.empty();
        if (enableCodeList.contains("191")) {
            companyMobileList = personalUserService.listByTypeAndName(COMPANY_USER, MOBILE_PHONE, PERSONAL_USER.OWNER_ID_NUMBER, PERSONAL_USER.OWNER_NAME);;
            codeEntityMap.put("191", companyMobileList);
        }
        // 单位固话一证多名
        List<PersonalUserEntity> companyTelephoneList = ListUtil.empty();
        if (enableCodeList.contains("192")) {
            companyTelephoneList = personalUserService.listByTypeAndName(COMPANY_USER, TELEPHONE, PERSONAL_USER.AGENT_ID_NUMBER, PERSONAL_USER.AGENT_NAME);
            codeEntityMap.put("192", companyTelephoneList);
        }
        // 行业移动一证多名
        List<PersonalUserEntity> industryMobileList = ListUtil.empty();
        if (enableCodeList.contains("193")) {
            industryMobileList = personalUserService.listByTypeAndName(INDUSTRY_USER, MOBILE_PHONE, PERSONAL_USER.PIC_ID_NUMBER, PERSONAL_USER.PIC_NAME);
            codeEntityMap.put("193", industryMobileList);
        }
        // 行业固话一证多名
        List<PersonalUserEntity> industryTelephoneList = ListUtil.empty();
        if (enableCodeList.contains("194")) {
            industryTelephoneList = personalUserService.listByTypeAndName(INDUSTRY_USER, TELEPHONE, PERSONAL_USER.PIC_ID_NUMBER, PERSONAL_USER.PIC_NAME);;
            codeEntityMap.put("194", industryTelephoneList);
        }
        // 一证多名所有数据
        if (enableCodeList.contains("195")) {
            List<PersonalUserEntity> multipleNameAllData = new ArrayList<>();
            multipleNameAllData.addAll(psrsonalMobileList);
            multipleNameAllData.addAll(personalTelephoneList);
            multipleNameAllData.addAll(companyMobileList);
            multipleNameAllData.addAll(companyTelephoneList);
            multipleNameAllData.addAll(industryMobileList);
            multipleNameAllData.addAll(industryTelephoneList);
            codeEntityMap.put("195", multipleNameAllData);
        }
        // 一证五号
        if (enableCodeList.contains("196")) {
            List<PersonalUserEntity> oneCardFiveNumbersList = personalUserService.listOneCardFiveNumbers();
            codeEntityMap.put("196", oneCardFiveNumbersList);
        }
    }

}
